<template>
  <Dialog v-model="dialogVisible" :title="dialogTitle" width="70%">
    <el-form
      ref="formRef"
      v-loading="formLoading"
      :model="formData"
      :rules="formRules"
      label-width="110px"
    >
      <el-row>
        <el-col :span="12">
          <el-form-item label="教学标题" prop="teachTitle">
            <el-input v-model="formData.teachTitle" placeholder="请输入教学标题" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="教学类型" prop="teachType">
            <el-select v-model="formData.teachType" placeholder="请选择">
              <el-option
                v-for="item in categoryList"
                :key="item.teachTypeId"
                :label="item.name"
                :value="item.teachTypeId"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="教学简介" prop="remark">
            <el-input v-model="formData.remark" placeholder="请输入教学简介" clearable />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="教学封面" prop="teachCove">
            <el-popover placement="right" :width="300" trigger="hover">
              <template #reference>
                <UploadImg v-model="formData.teachCove" height="80px" />
              </template>
              <el-input
                v-model="formData.teachCove"
                :rows="3"
                type="textarea"
                placeholder="可直接输入图片网络链接地址"
              />
            </el-popover>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="教学视频" prop="teachVideo">
            <UploadFile
              v-model="formData.teachVideo"
              :file-type="['mp4']"
              :limit="1"
              :file-size="100"
            />
            <el-input
              v-model="formData.teachVideo"
              :rows="3"
              type="textarea"
              placeholder="可直接输入视频网络链接地址"
            />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="商品关联" prop="spuId">
            <el-tag v-if="formData.spuId" class="mr-10px">
              {{ spuList.find((item) => item.id === formData.spuId)?.name }}
            </el-tag>
            <el-button @click="spuSelectRef?.open()">选择商品</el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <el-button :disabled="formLoading" type="primary" @click="submitForm">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
  <ProductSelect ref="spuSelectRef" @confirm="selectSpu" />
  <!--  <SpuSelect ref="spuSelectRef" @confirm="selectSpu" />-->
</template>
<script lang="ts" setup>
import { DICT_TYPE, getBoolDictOptions, getIntDictOptions } from '@/utils/dict'
import * as ArticleApi from '@/api/mall/promotion/article'
import * as ArticleCategoryApi from '@/api/mall/promotion/articleCategory'
import * as ProductSpuApi from '@/api/mall/product/spu'
import * as teachApi from '@/api/service/teach/index'

import { SpuSelect } from '@/views/mall/promotion/components'
import { UploadImg } from '@/components/UploadFile'

defineOptions({ name: 'AfterSaleForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  teachType: undefined,
  teachTitle: undefined,
  author: undefined,
  teachCove: undefined,
  introduction: undefined,
  sort: 0,
  status: 0,
  spuId: 0,
  deviceId: 0,
  recommendHot: false,
  recommendBanner: false,
  teachContent: undefined,
  teachVideo: ''
})
const formRules = reactive({
  teachType: [{ required: true, message: '分类id不能为空', trigger: 'blur' }],
  teachTitle: [{ required: true, message: '教学标题不能为空', trigger: 'blur' }],
  teachCove: [{ required: true, message: '教学封面图片地址不能为空', trigger: 'blur' }],
  sort: [{ required: true, message: '排序不能为空', trigger: 'blur' }],
  status: [{ required: true, message: '状态不能为空', trigger: 'blur' }],
  spuId: [{ required: true, message: '商品关联id不能为空', trigger: 'blur' }],
  deviceId: [{ required: true, message: '商品关联id不能为空', trigger: 'blur' }],
  recommendHot: [{ required: true, message: '是否热门(小程序)不能为空', trigger: 'blur' }],
  recommendBanner: [{ required: true, message: '是否轮播图(小程序)不能为空', trigger: 'blur' }],
  teachContent: [{ required: true, message: '教学内容不能为空', trigger: 'blur' }]
})
const formRef = ref() // 表单 Ref
const spuSelectRef = ref() // 商品和属性选择 Ref
const selectSpu = async (spuId: number, skuIds: number[], spu: any) => {
  formData.value.spuId = spuId
  formData.value.deviceId = spuId
  formData.value.deviceName = spu.name // 赋值商品名称
  formData.value.deviceTypeId = spu.categoryId // 赋值商品分类ID
  //   重新获取产品信息用于回显
  const spuDatas = await getSpuList(spuId)
  spuList.value = spuDatas
}
const spuList = ref<ProductSpuApi.Spu[]>([])

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 修改时，设置数据
  formData.value.teachVideo = ''
  if (id) {
    formLoading.value = true
    try {
      formData.value = await teachApi.getTeach(id)
      formData.value.spuId = formData.value.deviceId
      // 进来后获取指定ID的产品列表用于商品名称回显
      const spuDatas = await getSpuList(formData.value.deviceId)
      spuList.value = spuDatas
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗
// 根据SPUID获取商品列表信息
const getSpuList = async (spuId: any) => {
  const res = await ProductSpuApi.getSpuDetailList([spuId])
  console.log(res)
  return res
}
/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  if (!formRef) return
  const valid = await formRef.value.validate()
  if (!valid) return
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as ArticleApi.ArticleVO
    if (formType.value === 'create') {
      await teachApi.createTeach(data)
      message.success(t('common.createSuccess'))
    } else {
      await teachApi.updateTeach(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    teachType: undefined,
    teachTitle: undefined,
    author: undefined,
    teachCove: undefined,
    introduction: undefined,
    sort: 0,
    status: 0,
    spuId: 0,
    deviceId: 0,
    recommendHot: false,
    recommendBanner: false,
    teachContent: undefined,
    teachVideo: ''
  }
  formRef.value?.resetFields()
}

const categoryList = ref<ArticleCategoryApi.ArticleCategoryVO[]>([])
onMounted(async () => {
  const data = await teachApi.getTeachTypeList()
  categoryList.value = data.list
  spuList.value = await ProductSpuApi.getSpuSimpleList()
})
</script>
